import sqlite3, datetime, time
from shared_resources import *

while True:
	initial_time = time.time()
	
	if datetime.datetime.now().hour == 22:
		sql_connection = sqlite3.connect(global_vars["database"])
		sql_cursor = sql_connection.cursor()
		# Delete unconfirmed lessons if they are within 2 days
		sql_cursor.execute("""delete from lessons where confirmed = 0 and start_time < ?""", (time.time() + 2 * 24 * 60 * 60,))
		# Remove old availability data
		sql_cursor.execute("""delete from teacher_schedule where start_time < ?""", (time.time() - 7 * 24 * 60 * 60,))
		sql_connection.commit()
		
		# Send emails to students if they have a lesson coming up in two days
		classes = []
		db_rows = sql_cursor.execute("""select class_id from lessons where start_time > ? and end_time < ?""", (time.time() + 1 * 24 * 60 * 60, time.time() + 2 * 24 * 60 * 60))
		for row in db_rows:
			classes.append(row[0])
		
		students = []
		for class_id in classes:
			db_rows = sql_cursor.execute("""select (select email from students where id = student_id) from student_classes where class_id = ?""", (class_id,))
			for row in db_rows:
				if row[0] != "":
					students.append(row[0])
		
		for student_email in set(students):
			if not send_email(student_email, t(global_vars["mail_messages"]["student_lesson_reminder"][0], (), True), t(global_vars["mail_messages"]["student_lesson_reminder"][1], (), True)):
				result += 'Error sending mail to user '+student_email

		sql_cursor.close()
		sql_connection.close()
	
	time.sleep(60*60 + initial_time-time.time()) # Adjust for time spent during operations

